//
//  FMSQLiteViewController.m
//  WeEsion
//
//  Created by reylen on 15/12/17.
//  Copyright © 2015年 fdauto. All rights reserved.
//

#import "FMSQLiteViewController.h"
#import "FMSQLiteManager.h"
#import "FMSQLiteDetailViewController.h"

@interface FMSQLiteViewController ()<UITableViewDataSource,UITableViewDelegate>{
}

@property (retain, nonatomic) UITableView* tableView;

@property (retain, nonatomic) NSString* filePath;
@property (copy, nonatomic) NSArray* tableListArray;

@end

@implementation FMSQLiteViewController

- (void)dealloc
{
    [[self sqliteManager] closeSQLiteDB];

}

- (instancetype)initWithFilePath:(NSString *) filePath
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.filePath = filePath;
    }
    return self;
}

- (FMSQLiteManager *) sqliteManager {
    FMSQLiteManager* sqliteManager = [FMSQLiteManager sharedManager];
    return sqliteManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"SQLite";
    self.view.backgroundColor = [UIColor whiteColor];
    [[self sqliteManager] openSQLiteDBWithPath:_filePath];
    self.tableListArray = [[self sqliteManager] queryTableFromDB];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tableListArray.count;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* identifier = @"Identifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.numberOfLines = 2;
    }
    
    cell.textLabel.text = [[self.tableListArray objectAtIndex:indexPath.row] lowercaseString];
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FMSQLiteDetailViewController* detail = [[FMSQLiteDetailViewController alloc] initWithStyle:UITableViewStylePlain tableName:[self.tableListArray objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:detail animated:YES];
}

@end
